<template>
  <div id="page">
    <img src="/static/images/logo.png">
    <img v-if="loading" class="animation_style" src="/static/images/loading.png">
    <div  v-if="loading">{{msg}}</div>
    <div class="msg" v-if="!loading&&isRefresh">定位失败</div>
    <div class="choose-button" v-if="!loading&&isRefresh" @click="refresh()">重新定位</div>
  </div>	

</template>
<script>
    import axios from 'axios'
    import router from '../router/router'
    export default {
        data: function() {
            return {
                "loading":true,
                "isRefresh":true,
                "userinfo":false,
                "banner":false,
                "msg":"欢迎光临!!!"
            }
        },
        // destroyed:function () {
        //    store.set("code", null);
        // },
        created: function() {

            this.$store.commit('changeIndexConf', {
                isFooter: false
            });
            // store.clear();
             function getUrlValue() {
                var qs = (location.search.length > 0 ? location.search.substring(1) : ""),
                    args = {},
                    items = qs.length ? qs.split("&") : [],
                    item = null,
                    name = null,
                    value = null,
                    i = 0,
                    len = items.length;
                for (i = 0; i < len; i++) {
                    item = items[i].split("=");
                    name = decodeURIComponent(item[0]);
                    value = decodeURIComponent(item[1]);
                    if (name.length) {
                        args[name] = value;
                    }
                }
                return args;
            }
            var arg = getUrlValue();

           if (arg.code!=undefined) {
             store.set("code", arg.code);
             store.set("doorKey", arg.shopCode_doorOpenWay);
             store.set("timer", 0);
             this.getCode();
           }
        },
        mounted: function() {
            if(store.get("code")!=null){
               this.getUserInfo();
            }
        },
        methods: {
            getCode:function(){
                 var _self = this;
            axios.get("/getWxOpenId.do?code=" + store.get('code'))
                .then(function(response) {
                    if (response.data.code == 200) {
                        store.set("user", response.data.obj);
                        store.set("position", "");
                        store.set("shopName", "");
                        store.set("userInfo", "");
                        store.set("isReload","");
                        store.set("reload",false);
                        window.location.replace("/?#/index");  
                    } else {
                    }
                })
                .catch(function(error) {
                });
            },
            getUserInfo:function(){
              var _self = this;
                axios.get("/autoLogin.do?openId=" + store.get('user'))
                    .then(function(response) {
                        if (response.data.code == 200) {
                            store.set("userInfo", JSON.stringify(response.data));

                            _self.openDoor(store.get("doorKey"));
                            _self.registered();  
                        } else if(response.data.code==404){
                           _self.registered();      
                        }
                        else{
                          _self.msg="获取用户信息失败";
                        }
                      // window.location.replace("/?#/position");
                    })
                    .catch(function(error) {

                    });
            },registered: function() {
               this.loading=true;
               this.msg="正在获取授权...";
                var xmUrl = location.href.split('#')[0];
                axios.get('/auth/signature.do?url=' + xmUrl)
                    .then(function(response) {
                        var xmappId = response.data.appId;
                        var xmtimestamp = response.data.timestamp;
                        var xmnonceStr = response.data.nonceStr;
                        var xmsignature = response.data.signature;
                        wx.config({
                            debug: false,
                            appId: xmappId,
                            timestamp: xmtimestamp,
                            nonceStr: xmnonceStr,
                            signature: xmsignature,
                            jsApiList: [
                                'checkJsApi',
                                'onMenuShareTimeline',
                                'onMenuShareAppMessage',
                                'onMenuShareQQ',
                                'onMenuShareWeibo',
                                'hideMenuItems',
                                'showMenuItems',
                                'hideAllNonBaseMenuItem',
                                'showAllNonBaseMenuItem',
                                'translateVoice',
                                'startRecord',
                                'stopRecord',
                                'onRecordEnd',
                                'playVoice',
                                'pauseVoice',
                                'stopVoice',
                                'uploadVoice',
                                'downloadVoice',
                                'chooseImage',
                                'previewImage',
                                'uploadImage',
                                'downloadImage',
                                'getNetworkType',
                                'openLocation',
                                'getLocation',
                                'hideOptionMenu',
                                'showOptionMenu',
                                'closeWindow',
                                'scanQRCode',
                                'chooseWXPay',
                                'openProductSpecificView',
                                'addCard',
                                'chooseCard',
                                'openCard'
                            ]
                        });
                    })
                    .catch(function(error) {
                        _self.$store.commit('changeIndexConf',   {                    
                        isToast:  true,
                        toastTip:   "授权失败"                
                        });
                    });

                wx.error(function(res) {
                });
                var _self = this;
                wx.ready(function(msg) { 
                   _self.positionAction();
                });
               
            },refresh:function(){
              store.set("timer","one");
              window.location.reload();
            },
            openDoor:function(key){
              if (key=="undefined") return;
                axios.get("/shop/scanRqOpenDoor.do?shopCode="+key.split("_")[0]+"&doorOpenWay="+key.split("_")[1])
                .then(function(response) {
                    
                })
                .catch(function(error) {
                });

            },
            positionAction:function(){
            var _self=this;
             _self.loading=true;
            _self.msg="定位中,请等待..."
            
              var timer=setTimeout(function() {
                if (store.get("position")=="") {
                _self.loading=false;
                if (store.get("timer")=="one") {
                _self.isRefresh=false;
                router.replace("/chooseShop");
               }
                }else{
                  router.replace("/first");  
                }
              },3000);
            
         
              wx.getLocation({
              type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
             success: function (res) {
             var latitude = res.latitude==undefined||res.latitude=="undefined"?res.latitude=0:res.latitude; // 纬度，浮点数，范围为90 ~ -90
             var longitude = res.longitude==undefined||res.longitude=="undefined"?res.longitude=0:res.longitude; // 
             var speed = res.speed; // 速度，以米/每秒计
             var accuracy = res.accuracy; // 位置精度
              axios.get('/shop/relateShop.do?longitude='+res.longitude+'&latitudes='+res.latitude)
             .then(function (response) {
             var schoolArr=new Array();
             schoolArr=response.data;
             store.set("position",schoolArr[0].shopCode);
             store.set("shopName", schoolArr[0].shopName);
             if (store.get('userInfo')=="") {
                if (schoolArr[0].shopType==1) {
                  router.replace("/unmannedLogin");
                }else{
                 router.replace("/login");
                }
               
              }else{

                 router.replace("/first");
              }
            })
           .catch(function (error) {
            store.set("position","XM0001");
            store.set("shopName", "点我,重新定位");
            router.replace("/first");
            });
          },
          fail:function () {
            _self.loading=false;
            _self.msg=""
            _self.$store.commit('changeIndexConf',   {                    
                        isToast:  true,
                        toastTip:   "网络异常,刷新或者重新进入"                
                        });
               }
          });
          }
        }

    }
</script>
<style lang="scss" scoped>
    @import "../../static/css/first.scss";
</style>
